
init();

async function init() {
  const res = await fetch(`/models.json?${Math.random()}`);
  const { models } = await res.json();
  
  const container = document.querySelector("#main");

  models.forEach((model) => {
    const { name, id, animation } = model;
    const modelEl = document.createElement("div");
    modelEl.className = "model-item";
    modelEl.setAttribute("data-id", id);
    modelEl.setAttribute("data-name", name);

    modelEl.innerHTML = `
      <div class="model-thumb" style="background-image: url(/thumbs/${id}.jpg)"></div>
      <div class="model-info">
        <div class="model-info-text">${name}${animation ? "<span>[有动画]<span>" : ""}</div>
      </div>
    `;

    container.appendChild(modelEl);
  });
  container.addEventListener("click", (e) => {
    let target = e.target;
    while (target.className !== "model-item" && target.tagName !== "BODY") {
      target = target.parentNode;
    }
    const { id, name } = target.dataset;
    downloadGlb(id, name);
  })
}

function downloadGlb(id, name) {
  const a = document.createElement("a");
  a.href = `/models/${id}.glb`;
  a.download = `${name}.glb`;
  a.click();
}